package com.qf.controller;

import com.qf.pojo.Admin;
import com.qf.service.AdminService;
import com.qf.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 管理员登录后台
 */

@WebServlet("/admin_login")
public class AdminLogin extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //处理乱码:post/响应乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //先处理验证码:  验证码存储在服务器端HttpSession
        //获取前提的参数
        String adminname = request.getParameter("adminname");
        String adminpassword = request.getParameter("adminpassword");
        //获取验证码
        String code = request.getParameter("code");

        //获取服务器端存储验证码
        //服务器端:
        //request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
        //获取session
        HttpSession session = request.getSession();
        //从session域获取CHECKCODE_SERVER绑定的内容
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        //一次性验证:
        //使用完毕之后,应该将上一次的服务器端段的验证码删除
        session.removeAttribute("CHECKCODE_SERVER");

        //判断前台输入的验证码和服务器端存储的验证码是否一致
        if( !code.equalsIgnoreCase(checkcode_server) || code==null){
            //给request域中存储一个信息
            request.setAttribute("msg","验证码错误");
            //请求转发到admin_login.jsp
            request.getRequestDispatcher("/admin/admin_login.jsp").forward(request,response);

        }

        //调用业务接口
        AdminService adminService = new AdminServiceImpl() ;
        boolean flag = adminService.isLogin(adminname, adminpassword);
        //封装管理员数据
        Admin admin = new Admin(adminname,adminpassword) ;
        if(flag){
            //登录成功
            //将我们的Admin实体 存储session域中
            session.setAttribute("admin",admin);

           //跳转主页
            request.getRequestDispatcher("/admin/admin_index.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","登录失败");
            request.getRequestDispatcher("/admin/admin_login.jsp").forward(request,response);
        }

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
